package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private DictFeignClient dictFeignClient;

    /**
     * 添加医院信息
     *
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        //1 把paramMap变成对象,使用fastjson
        //1.1 把map变成json字符串
        String jsonString = JSONObject.toJSONString(paramMap);
        //1.2 把json字符串转换对象
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);

        //2、根据医院编号查询医院信息是否已经添加
        Hospital existHospital = hospitalRepository.findByHoscode(hospital.getHoscode());

        //如果已经添加过，则修改
        if (existHospital != null) {
            hospital.setId(hospital.getId());
            hospital.setCreateTime(existHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        } else {
            //如果没有添加，则添加
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
        hospitalRepository.save(hospital);
    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.findByHoscode(hoscode);
    }

    /**
     * 分页查询
     *
     * @param page    当前页码
     * @param limit   每页记录数
     * @param hosname 查询条件
     */
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, String hosname) {
        Sort sort = Sort.by(Sort.Direction.DESC, "creatTime");

        PageRequest pageRequest = PageRequest.of(page - 1, limit, sort);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        Hospital hospital = new Hospital();
        hospital.setHosname(hosname);
        Example<Hospital> example = Example.of(hospital, matcher);

        Page<Hospital> pageModel = hospitalRepository.findAll(example, pageRequest);
        //遍历循环将数据字典添加进去
        pageModel.getContent().stream().forEach(item -> {
            this.packHospital(item);
        });

/*
        List<Hospital> content = pageModel.getContent();
        content.forEach(item -> {
            this.packHospital(item);
        });
*/

        return pageModel;
    }

    /**
     * 修改上线/下线 状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(String id, Integer status) {
        Hospital hospital = hospitalRepository.findById(id).get();
        hospital.setStatus(status);
        hospital.setCreateTime(new Date());
        hospitalRepository.save(hospital);
    }

    /**
     * 医院详情
     *
     * @param id
     * @return
     */
    @Override
    public Hospital show(String id) {
        Hospital hospital = hospitalRepository.findById(id).get();
        return this.packHospital(hospital);
    }

    /**
     * 根据条件查询医院列表
     *
     * @param keywords 医院名称：模糊匹配
     * @param levelId： 医院级别：精确匹配
     * @param areaId：  医院地区：精确匹配
     * @return
     */
    @Override
    public List<Hospital> selectList(String keywords, String levelId, String areaId) {
        ExampleMatcher matching = ExampleMatcher.matching()
                //根据网页前端所需要的的参数 查询
                .withMatcher("hosname", ExampleMatcher.GenericPropertyMatchers.contains()) //模糊查询
                .withMatcher("hostype", ExampleMatcher.GenericPropertyMatchers.exact()) //精确查询
                .withMatcher("districtCode", ExampleMatcher.GenericPropertyMatchers.exact()); //精确查询

        Hospital hospital = new Hospital();
        hospital.setHosname(keywords);
        hospital.setHostype(levelId);
        hospital.setDistrictCode(areaId);
        hospital.setStatus(1); //已上线
        //对象hospital 根据 条件匹配器 matching 查询(模糊查询/精确查询)
        Example<Hospital> example = Example.of(hospital, matching);

        List<Hospital> list = hospitalRepository.findAll(example);
        //封装医院等级数据
        list.stream().forEach(this::packHospitalType);

        return list;
    }

    /**
     * 医院详情信息展示
     *
     * @param hoscode
     * @return
     */
    @Override
    public Hospital getDetail(String hoscode) {
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        this.packHospital(hospital);
        return hospital;
    }

    /**
     * 封装数据
     *
     * @param hospital
     * @return
     */
    public Hospital packHospital(Hospital hospital) {
        //远程调用
        //获取医院类型
        String hosptypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
        //获取省份信息
        String provinceString = dictFeignClient.getName(null, hospital.getProvinceCode());
        //获取市区信息
        String cityString = dictFeignClient.getName(null, hospital.getCityCode());
        //获取辖区信息
        String districtString = dictFeignClient.getName(null, hospital.getDistrictCode());

        //key值根据前端赋值确定
        hospital.getParam().put("hostypeString", hosptypeString);
        //详细地址: --> 省 + 市 + 区 + 详情地址
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }

    /**
     * 封装医院等级
     *
     * @param hospital
     * @return
     */
    public Hospital packHospitalType(Hospital hospital) {
        //远程调用
        //获取医院类型
        String hosptypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());

        //key值根据前端赋值确定
        hospital.getParam().put("hostypeString", hosptypeString);

        return hospital;
    }
}